In C, macros are pre-processor directives that allow defining symbolic names or constants. They are created using the #define pre-processor directive and provide a way to perform text replacement before the actual compilation of the code.
To define a macro in C, use the #define directive followed by the macro name and its value (replacement text).
#define MACRO_NAME value
#include <stdio.h>
// Define macros for maximum and minimum functions
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define MIN(a, b) ((a) < (b) ? (a) : (b))
// Define macro for constant value
#define PI 3.1415926535
int main() {
int x = 10, y = 20;
int maxVal = MAX(x, y);
int minVal = MIN(x, y);
printf("Maximum value: %d\n", maxVal); //
Maximum value: 20
printf("Minimum value: %d\n", minVal); //
Minimum value: 10
double radius = 5.0;
double area = PI * radius * radius;
printf("Area of circle: %lf\n", area); // Area of circle: 78.539816
return 0;
}
Maximum value: 20
Minimum value: 10
Area of circle: 78.539816
Note: Macros are handled by the pre-processor, which performs textual replacement before the actual compilation of the code. Be cautious when defining macros, as they can lead to unexpected results when used improperly, such as multiple evaluations of arguments. To avoid such issues, can wrap arguments in parentheses within the macro definition, as shown in the sample code for MAX() and MIN().
What is a macro in C?
What does a macro do in C?
What symbol is used to define a macro in C?
What is the primary purpose of macros in C?
What is the benefit of using macros in C?